package com.clt.ess.service.impl;


import com.clt.ess.CABeen.CheckResultPackage;
import com.clt.ess.base.Constant;
import com.clt.ess.dao.ICertificateDao;
import com.clt.ess.dao.IIssuerUnitDao;
import com.clt.ess.entity.Certificate;
import com.clt.ess.entity.IssuerUnit;
import com.clt.ess.service.ICAService;
import com.clt.ess.service.ICertificateService;
import com.clt.ess.service.IGjzwService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.clt.ess.utils.CertificateUtil.CreatePfxFile;

import static com.clt.ess.utils.StringUtils.*;
import static com.clt.ess.utils.dateUtil.strToDate;
import static com.clt.ess.utils.uuidUtil.getUUID;

@Service
public class CertificateServiceImpl implements ICertificateService {

    @Autowired
    private ICertificateDao certificateDao;
    @Autowired
    private IIssuerUnitDao issuerUnitDao;
    @Autowired
    private ICAService caService;

    /**
     * 添加证书
     * @param certificate
     * @return 返回添加数据的主键ID
     */
    @Override
    public String addCertificate(Certificate certificate) {

        certificate.setState(Constant.STATE_YES);

        certificate = EncryptCert(certificate);

        //执行add动作，获取返回结果
        int result = certificateDao.addCertificate(certificate);

        DecryptCert(certificate);
        if(result == 1 ){
            return certificate.getCertificateId();
        }else{
            return null;
        }
    }
    /**
     * 根据证书颁发机构生成证书
     */
    @Override
    public  Map<String, String> createCerFileAndPfx(Certificate certificate) {
        try{
            IssuerUnit issuerUnit = issuerUnitDao.findIssuerUnitById(certificate.getIssuerUnitId());
            String algorithm = certificate.getAlgorithm();
            String sC = certificate.getCountry();
            String sS = certificate.getProvince();
            String sL = certificate.getCity();
            String sO = certificate.getCertUnit();
            //部门由单位代替（暂时）
            String sOU = certificate.getCertDepartment();
            String sDN = certificate.getCerName();
            //起始时间
            Date dateStart = strToDate(certificate.getStartTime());
            Date dateEnd  = strToDate(certificate.getEndTime());
            String sPwd = getDecryptPwd(certificate.getCerPsw());
            return  CreatePfxFile(sC,sS,sL,sO,sOU,sDN,dateEnd,dateStart,
                    sPwd,algorithm,issuerUnit);

        }catch (Exception e){
            return null;
        }
    }

    @Override
    public List<Certificate> findCertificate(Certificate certificate) {
        List<Certificate> certificateList = new ArrayList<>();
        certificateList = certificateDao.findCertificate(certificate);
        for (Certificate certificate1 : certificateList){
            certificate1 = DecryptCert(certificate1);
        }
        return certificateList;
    }

    @Override
    public Certificate findCertificateById(String certificateId) {
        return DecryptCert(certificateDao.findCertificateById(certificateId));
    }

    @Override
    public boolean updateCertificate(Certificate certificate) {

        int result = certificateDao.updateCertificate(EncryptCert(certificate));
        DecryptCert(certificate);
        if(result == 1 ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 加密证书信息
     * @param certificate
     * @return
     */
    private Certificate EncryptCert(Certificate certificate){
        if (certificate==null){
            return null;
        }

        //执行加密信息
        //加密证书信息加密
        if (certificate.getPfxBase64()!=null){
            certificate.setPfxBase64(getEncryptString(certificate.getPfxBase64()));
        }
        //签名证书加密
        if (certificate.getCerBase64()!=null){
            certificate.setCerBase64(getEncryptString(certificate.getCerBase64()));
        }
        //公钥信息加密
        if (certificate.getPublicKey()!=null){
            certificate.setPublicKey(getEncryptString(certificate.getPublicKey()));
        }
        //证书起始时间加密
        if (certificate.getStartTime()!=null){
            certificate.setStartTime(getEncryptString(certificate.getStartTime()));
        }
        //证书到期时间加密
        if (certificate.getEndTime()!=null){
            certificate.setEndTime(getEncryptString(certificate.getEndTime()));
        }
        //密文结构加密
        if (certificate.getEncKeyProtection()!=null){
            certificate.setEncKeyProtection(getEncryptString(certificate.getEncKeyProtection()));
        }
        return certificate;
    }

    /**
     * 解密证书信息
     * @param certificate
     * @return
     */
    private Certificate DecryptCert(Certificate certificate){
        if (certificate==null){
            return null;
        }

        //执行加密信息
        //加密证书信息加密
        if (certificate.getPfxBase64()!=null){
            certificate.setPfxBase64(getDecryptString(certificate.getPfxBase64()));
        }
        //签名证书加密
        if (certificate.getCerBase64()!=null){
            certificate.setCerBase64(getDecryptString(certificate.getCerBase64()));
        }
        //公钥信息加密
        if (certificate.getPublicKey()!=null){
            certificate.setPublicKey(getDecryptString(certificate.getPublicKey()));
        }
        //证书起始时间加密
        if (certificate.getStartTime()!=null){
            certificate.setStartTime(getDecryptString(certificate.getStartTime()));
        }
        //证书到期时间加密
        if (certificate.getEndTime()!=null){
            certificate.setEndTime(getDecryptString(certificate.getEndTime()));
        }
        //密文结构加密
        if (certificate.getEncKeyProtection()!=null){
            certificate.setEncKeyProtection(getDecryptString(certificate.getEncKeyProtection()));
        }
        return certificate;


    }






    @Override
    public Certificate getCertFormCA(String OrganizationName, String certType, String publicKey,
                                String NotBefore, String NotAfter, String sealCodeData) {
        CheckResultPackage checkResultPackage = caService.getCertFormCA(OrganizationName,sealCodeData,
                certType,publicKey, NotBefore,NotAfter);

        if (checkResultPackage ==null){
//            return "申请证书失败！";
            return null;
        }
        //申请证书并进行备案
        Certificate certificate = new Certificate();
        certificate.setCertificateId(getUUID());
        certificate.setStartTime(NotBefore);
        certificate.setEndTime(NotAfter);
        certificate.setPfxBase64(checkResultPackage.getEncCert());
        certificate.setCerBase64(checkResultPackage.getSignCert());
        certificate.setEncKeyProtection(checkResultPackage.getEncKeyProtection());
        certificate.setPublicKey(publicKey);
        certificate.setCerClass(certType);

        String cerid = addCertificate(certificate);
        if (cerid==null){
            //添加证书失败
            return null;
        }
        return certificate;
    }
}
